/* eslint-disable default-case */
/* eslint-disable array-callback-return */
import { message } from 'antd';
import {
  getQuoInfo,
  getPdData,
  getDownloadInfo,
  getUploadProgress,
  getDownloadInfoQuo,
  uploadFileQuotation,
} from '@/services/batchadjust';
import { matchDict } from '@/utils/utils';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'batchquo';
const ModelAddEmp = {
  namespace,
  state: {
    formFieldsValue: {}, // 表单域
    expandForm: false, // 展开收起
    data: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
      batchAdjType: '1', // 调整类型

      // 调整服务费
      sendSuppId: undefined,
      contId: undefined,
      custId: undefined,
      oldQuoId: undefined,
      quoId: undefined,
    },
    customerNameList: [],
    supplyContList: [],
    contList: [],
    quoList: [],
    supplyList: [],
    isSameComy: true,
    suppReplaceCorpId: '', // 当前角色所在公司id
    quoPdList: [], // 新旧报价单表格数据
    detailInfo: { packList: [] },
    cacheKey: null, // 缓存信息
    isGoBack: false,
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/sendempchangeQuo/exportErrorExcel', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
  },
  effects: {
    // 获取报价单信息
    *fetchQuoInfo({ payload }, { call, put, select }) {
      const response = yield call(getQuoInfo, payload);
      const dictCode = yield select(state => state.publicdata.dictCode);
      if (response.success && response.data) {
        const detailInfo = response.data;
        if (detailInfo.packList.length) {
          detailInfo.packList.map(pack => {
            if (pack.listQuoPd.length) {
              pack.listQuoPd.map(pd => {
                if (pd.listAttr.length) {
                  pd.listAttr.map(attr => {
                    const temp = attr;
                    temp.attrValName = [];
                    temp.name = '';
                    if (attr.attrValList.length) {
                      attr.attrValList.forEach(item => {
                        attr.attrValName.push(matchDict(dictCode[attr.dictType], item));
                      });
                      temp.name = attr.attrValName.join(',');
                    }
                  });
                }
              });
            }
          });
        }
        yield put({
          type: 'updateModelData',
          payload: {
            detailInfo,
          },
        });
      } else {
        message.warning(`${response.message || '获取报价单信息：服务端错误！'}`);
      }
      return response;
    },
    // 获取新旧报价单数据
    *getPdList({ payload }, { call, put }) {
      const response = yield call(getPdData, payload);
      yield put({
        type: 'getList',
        payload: {
          data: [],
        },
      });
      if (response.success && response.data) {
        // const isQuoChanged = response.data.some(
        //   item =>
        //     item.newQuo.diff ||
        //     (item.newQuo.attrList &&
        //       item.newQuo.attrList.length &&
        //       item.newQuo.attrList.some(attr => attr.diff))
        // );
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '获取新旧报价单信息：服务端错误！'}`);
      }
    },
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call }) {
      const response = yield call(getDownloadInfo, payload);
      return response;
    },
    // 获取下载模板fileId fileName:报价单
    *getDownloadInfoQuo({ payload }, { call }) {
      const response = yield call(getDownloadInfoQuo, payload);
      return response;
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    *uploadFileWithProgress({ payload }, { call, put }) {
      try {
        const response = yield call(uploadFileQuotation, payload);
        if (response.success) {
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: response.data,
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.batchquo);
      const { cacheKey } = state;
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          cacheKey,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    // 获取新旧报价单列表
    getList(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        quoPdList: data,
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 公积金设置修改当前state数据
    accuUpdateModelData(state, { payload }) {
      const temp = state;
      if (payload.name === 'decWageFlag') {
        temp.batchQuery.decWageFlag = payload.state;
      } else {
        temp.batchQuery.lsPkgFlag = payload.state;
      }
      return {
        ...state,
      };
    },

    // 设置查询时保存的值
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },

  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
